package com.zd.commodity.action;

import java.beans.IntrospectionException;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import utils.Util;

import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.struts2.ServletActionContext;

import com.alibaba.fastjson.JSON;
import com.opensymphony.xwork2.ActionContext;
import com.zd.commodity.biz.IBaseBiz;

public abstract class BaseAction<T> {
	
	private IBaseBiz baseBiz;//业务逻辑层
	protected HttpServletRequest request = ServletActionContext.getRequest();
	protected HttpServletResponse response = ServletActionContext.getResponse();
	public HttpServletResponse getResponse() {
		response.setContentType("text/html;charset=UTF-8");
		return response;
	}
	
	public void responseWriter(String s) throws IOException{
		getResponse().getWriter().write(s);
	}
	
	//进入属性菜单  选择分类
	public String chooseCategory(){
		request.setAttribute("params", params);
		return "chooseCategoty";
	}
	/**
	 * fileName客户下载时的文件名。title和neededFields顺序必须一致
	 * @param fileName
	 * @param dataList
	 * @param title
	 * @param neededFields
	 * @throws Exception
	 */
	public void excelExport(String fileName,List<T> dataList,String[] title,String[] neededFields) throws Exception{
		XSSFWorkbook wb = new XSSFWorkbook();
		XSSFSheet sheet = wb.createSheet("sheet1");
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		//写入标题
		int tLength = title.length;
		sheet = Util.writeExcel(sheet, title);
		//遍历查询结果
		for (int i=0;i<dataList.size();i++) {
			String[] values = new String[tLength];
			for(int k=0;k<neededFields.length;k++){
				T t3 = dataList.get(i);
				Field field = t3.getClass().getDeclaredField(neededFields[k]);
				field.setAccessible(true);
				Object objectField = field.get(t3);
				if(field.getType().toString().endsWith("Date")){
					if(objectField!=null){
						Date date = (Date)objectField;
						values[k] = format.format(date);
					}
				}else{
					values[k]=objectField==null?"":objectField.toString();
				}
			}
			
			sheet = Util.writeExcel(sheet, values);
		}
		Util.outPutExcel(fileName, wb,request);
	}
	
	//默认的excel导出
	public void excelExport() throws Exception{
		XSSFWorkbook wb = new XSSFWorkbook();
		XSSFSheet sheet = wb.createSheet("sheet1");
		//获取列表
		List<T> list = baseBiz.getList(t1,t2,null);
		//按实体类字段名写入标题
		Field[] fields = list.get(0).getClass().getDeclaredFields();
		int fLength = fields.length;
		String[] titles = new String[fLength];
		for(int i=0;i<fLength;i++){
			titles[i]=fields[i].getName();
		}
		sheet = Util.writeExcel(sheet, titles);
		//遍历查询结果
		for (int i=0;i<list.size();i++) {
			//反射遍历字段
			Field[] fs = list.get(i).getClass().getDeclaredFields();
			String[] values = new String[fLength];
			for (int j=0;j<fLength;j++) {
				Field f = fs[j];
				f.setAccessible(true);
				String type = f.getType().toString();//得到此属性的类型
				Object value = f.get(list.get(i));
				values[j]=value.toString();
			}
			sheet = Util.writeExcel(sheet, values);
		}
		Util.outPutExcel("data", wb,request);
		/*ByteArrayOutputStream baos = new ByteArrayOutputStream();
		wb.write(baos);
		byte[] content = baos.toByteArray();
		HttpServletResponse response = ServletActionContext.getResponse();
		response.reset();
		response.setContentType("application/x-msdownload");
		response.addHeader("Content-Disposition", "attachment; filename=\"data.xlsx\"");
		ServletOutputStream outputStream = response.getOutputStream();
		outputStream.write(content, 0, content.length);
		outputStream.flush();*/
	}
	
	public void setBaseBiz(IBaseBiz baseBiz) {
		this.baseBiz = baseBiz;
	}

	private T t1;//查询条件
	public T getT1() {
		return t1;
	}
	public void setT1(T t1) {
		this.t1 = t1;
	}
	
	private T t2;//查询条件	
	public T getT2() {
		return t2;
	}
	public void setT2(T t2) {
		this.t2 = t2;
	}
	/**
	 * 列表
	 * @return
	 */
	public String list()
	{
		//获取列表
		List<T> list = baseBiz.getList(t1,t2,null);				
		ActionContext.getContext().put("list", list);
		return "list";
		
	}
	
	private int page;//页码
	private int rows;//每页记录数
		
	public int getPage() {
		return page;
	}
	public void setPage(int page) {
		this.page = page;
	}
	public int getRows() {
		return rows;
	}
	public void setRows(int rows) {
		this.rows = rows;
	}
	
	private String params;
	public String getParams() {
		return params;
	}
	public void setParams(String params) {
		this.params = params;
	}

	/**
	 * 列表(分页)
	 * @return
	 */
	public String listByPage()
	{	
		//将参数转型
		Object objparam=(Object)params;
		//页码换算
		if(page==0)
		{
			page=1;
		}
		if(rows==0)
		{
			rows=10;
		}	
		
		int firstResult=(page-1)*rows;
		//获取列表
		List<T> list = baseBiz.getListByPage(t1,t2,objparam, firstResult, rows);		
		//统计记录个数
		long count = baseBiz.getCount(t1,t2,objparam);
		long pageCount=count/rows;
		if(count%rows>0){
			pageCount++;
		}
		ActionContext.getContext().put("list", list);
		ActionContext.getContext().put("pageCount",pageCount);
		ActionContext.getContext().put("page",page);
		ActionContext.getContext().put("recordsCount",count);
		
		
		return "list";
	}
	
	private T t;//信息
	
	public T getT() {
		return t;
	}
	public void setT(T t) {
		this.t = t;
	}
	
	public String save()
	{
		if(method==null || method.equals(""))
		{
			return add();
		}else
		{
			request.setAttribute("page", page);
			return update();
		}
	}
	
	private String method;
		
	public String getMethod() {
		return method;
	}
	public void setMethod(String method) {
		this.method = method;
	}
	
	
	/**
	 * 增加
	 */
	public String add()
	{
		try {
			baseBiz.add(t);			
		} catch (Exception e) {			
			e.printStackTrace();
		}
		
		return listByPage();
	}
	
	/**
	 * 修改
	 */
	public String update()
	{
		try {
			baseBiz.update(t);	
			request.setAttribute("page", page);
		} catch (Exception e) {			
		
		}
		return listByPage();
	}
	
	private Long id;//主键
		
	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	/**
	 * 删除方法
	 */
	public String delete()
	{
		try {
			baseBiz.delete(id);		
			request.setAttribute("page", page);
		} catch (Exception e) {
			e.printStackTrace();
		}		
		return listByPage();
		
	}
	
	
	
	/**
	 * 	返回字符串的增删改
	 */	
	public String keep()
	{
		request.setAttribute("params", params);
		if(method==null || method.equals(""))
		{
			return increase();
		}else
		{
			request.setAttribute("page", page);
			return modify();
		}
	}
	
	/**
	 * 增加
	 */
	public String increase()
	{
		try {
			baseBiz.add(t);			
		} catch (Exception e) {			
			e.printStackTrace();
		}
		request.setAttribute("params", params);
		return "toshow";
	}
	
	/**
	 * 修改
	 */
	public String modify()
	{
		try {
			baseBiz.update(t);			
		} catch (Exception e) {			
		
		}
		request.setAttribute("page", page);
		request.setAttribute("params", params);
		return "toshow";
	}
	
	/**
	 * 删除
	 */
	public String remove()
	{
		try {
			baseBiz.delete(id);			
		} catch (Exception e) {
			e.printStackTrace();
		}		
		request.setAttribute("page", page);
		request.setAttribute("params", params);
		return "toshow";
		
	}
	
	/**
	 * 返回ajax结构返回体
	 * @param success
	 * @param message
	 * @return
	 */
	public String ajaxReturn(boolean success,String message,Object object){
		Map map = new HashMap();
		map.put("success", success);
		map.put("message", message);
		map.put("object", object);
		return JSON.toJSONString(map);
	}
	
	/**
	 * 输出信息
	 * @param jsonString
	 */
	public void write(String jsonString){
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		try {
			response.getWriter().print(jsonString);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * 查询实体
	 * @throws IntrospectionException 
	 * @throws InvocationTargetException 
	 * @throws IllegalAccessException 
	 */
	public String get()
	{		
		T t3 = (T) baseBiz.get(id);
		request.setAttribute("page", page);
		request.setAttribute("params", params);
		ActionContext.getContext().put("t", t3);
		ActionContext.getContext().put("method", "update");
		return "form";
	}
	//跳转到添加页面
	public String toAdd()
	{		
		request.setAttribute("params", params);
		return "toAdd";
	}
	
}
